import { Input, NavBar } from "antd-mobile"
import classnames from "classnames"
import { useHistory } from "react-router-dom"
import Icon from "@/components/Icon"
import styles from "./index.module.scss"
import { io, Socket } from "socket.io-client"
import { useEffect, useState, useRef, useLayoutEffect } from "react"
import { getToken } from "@/utils/token"

type ChatType = {
  message: string
  type: "user" | "xz"
}
const Chat = () => {
  const history = useHistory()
  const [chatList, setChatList] = useState<ChatType[]>([])
  const [value, setValue] = useState("")
  const socketRef = useRef<Socket>()
  const listRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    // 1 建立连接
    const socketio = io("http://toutiao.itheima.net", {
      // 参数
      query: {
        token: getToken().token,
      },
      // 连接方式
      transports: ["websocket"],
    })

    // 2 连接成功
    socketio.on("connect", () => {
      console.log("websocket 连接成功")
      // 让小智给你打个招呼
      setChatList([
        { message: "你好，我是小智", type: "xz" },
        { message: "你有什么疑问？", type: "xz" },
      ])
    })
    socketio.on("message", (data) => {
      setChatList((list) => [
        ...list,
        {
          message: data.msg,
          type: "xz",
        },
      ])
    })
    socketRef.current = socketio
    return () => {
      socketio.close()
    }
  }, [])

  const onSend = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.code !== "Enter" || value.trim() === "") return

    // 发送消息给服务器
    socketRef.current?.emit("message", {
      msg: value,
      timestamp: Date.now() + "",
    })

    setChatList([
      ...chatList,
      {
        type: "user",
        message: value,
      },
    ])

    setValue("")
  }
  useLayoutEffect(() => {
    const chatListDOM = listRef.current
    if (!chatListDOM) return

    chatListDOM.scrollTop = chatListDOM.scrollHeight
  }, [chatList])
  return (
    <div className={styles.root}>
      <NavBar className="fixed-header" onBack={() => history.go(-1)}>
        小智同学
      </NavBar>

      <div className="chat-list" ref={listRef}>
        {chatList.map((item, index) => {
          return (
            <div key={index} className={classnames("chat-item", item.type === "xz" ? "self" : "user")}>
              {item.type === "xz" ? <Icon type="iconbtn_xiaozhitongxue" /> : <img src="http://geek.itheima.net/images/user_head.jpg" alt="" />}
              <div className="message">{item.message}</div>
            </div>
          )
        })}
      </div>

      <div className="input-footer">
        <Input className="no-border" value={value} onChange={(value) => setValue(value)} onKeyDown={onSend} placeholder="请描述您的问题" />
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat
